package com.gqb.collection;

public class MyLinkedList<E> {
	private Node<E> headNode;
	private Node<E> tailNode;
	private int size=0;
	private int modCount=0;
	public void add(E valueE){
		Node<E> ele=new Node<E>(valueE);
		if(tailNode!=null){
			tailNode.next=ele;
			ele.prev=tailNode;
			tailNode=ele;
		}else {
			tailNode=ele;
			headNode=ele;
			headNode.prev=null;
		}
		size++;
	}
	
	public void add(int i,E valueE){
		Node<E> addNode=new Node<E>(valueE);
		if(i>size){//插入到最后
			tailNode.next=addNode;
			addNode.prev=tailNode;
		}else {
			Node<E> x=headNode;
			for (int j = 0; j < i-1; j++) {
				x=x.next;
			}
			x.prev.next=addNode;
			addNode.prev=x.prev;
			addNode.next=x;
			x.prev=addNode;
			tailNode=x;
		}
		size++;
	}
	
	public E get(int i){
		if(i>size||i<0)
			throw new IndexOutOfBoundsException();
		Node<E> x=headNode;
		for (int j = 0; j < i-1; j++) {
			x=x.next;
		}
		return x.valueE;
	}
	
	public E getFirst(){
		if(size>0){
			return headNode.valueE;
		}
		return null;
	}
	
	public E getLast(){
		if(size>0){
			return tailNode.valueE;
		}
		return null;
	}
	
	public E remove(int i){
		E valE;
		if(i>size)
			throw new IndexOutOfBoundsException();
		Node<E> x=headNode;
		for (int j = 0; j < i-1; j++) {
			x=x.next;
		}
		valE=x.valueE;
		remove(x);
		return valE;
	}
	
	private void remove(Node<E> node){
		if(node==tailNode){
			tailNode=node.prev;
			if(size>1)
				tailNode.next=null;
		}else if (node==headNode) {
			headNode=headNode.next;
			if(size>1){
				headNode.prev=null;
			}
		}else {
			node.next.prev=node.prev;
			node.prev.next=node.next;
		}
		size--;
		modCount++;
	}
	
	class Node<E>{
		private Node prev;
		private Node next;
		private E valueE;
		public Node(E valueE) {
			super();
			this.valueE = valueE;
		}
		public Node(Node prev, Node next, E valueE) {
			super();
			this.prev = prev;
			this.next = next;
			this.valueE = valueE;
		}
		
	}
	
	
	private class MyLinkedListIterator implements java.util.Iterator<E>{
		private E[] elements;
		private int size;
		
		
		@Override
		public boolean hasNext() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public E next() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void remove() {
			// TODO Auto-generated method stub
			
		}
		
	}


	@Override
	public String toString() {
		StringBuilder stBuilder=new StringBuilder();
		Node<E> x=headNode;
		for (int i = 0; i <size; i++) {
			stBuilder.append("["+x.valueE+"]");
			x=x.next;
		}
		return stBuilder.toString();
	}
	
	
}
